package com.gxy.learn.upload.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gxy.learn.upload.config.TaskConfig;
import com.gxy.learn.upload.service.UploadService;
import com.gxy.learn.upload.utils.CommandClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * Description:
 * author: Gaoxueyong
 * Create at: 2023/2/8 16:39
 */
@Service
public class UploadServiceImpl implements UploadService {
    private static final Logger log = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Autowired
    private TaskConfig taskConfig;

    @Override
    public String upload(MultipartFile muFile, String channel, String env, String version) {
        File file = transferToFile(muFile,channel,env,version);
        if (null == file) {
            return "上传失败！";
        }
        try {
            CommandClient instance = CommandClient.getInstance(taskConfig.getIp(), taskConfig.getPort(), taskConfig.getName(), taskConfig.getPassword());
            Map<String, Object> result = instance.uploadFile(file, file.length(), taskConfig.getTargetPath(), null);
//            Map<String, Object> result = new HashMap<>();
//            result.put("success",true);
            log.info("文件上传响应：result = {}", JSONObject.toJSON(result));
            Boolean success = (Boolean) result.getOrDefault("success", Boolean.FALSE);
            log.info("文件[{}]上传[{}]！", file.getName(), success ? "成功" : "失败");
            return "上传成功！";
        } catch (Exception e) {
            log.error("文件[{}]上传[失败]！", file.getName(), e);
            return "上传失败！";
        }finally {
            file.deleteOnExit();
            log.info("临时文件[{}]删除[成功]！", file.getName());
        }
    }

    private File transferToFile(MultipartFile multipartFile, String channel, String env, String version) {
//        选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        String[] tempArray = multipartFile.getOriginalFilename().split("\\.");
        String suffix = tempArray[1];
        String fileName = String.format("%s-%s-%s.%s", channel, env, version,suffix);
        File file = null;
        try {
            file = new File(String.format("%s%s%s",new File("").getCanonicalPath(),File.separator,fileName));
            multipartFile.transferTo(file);
            log.info("文件名称由[{}]修改为[{}][{}]", multipartFile.getOriginalFilename(),fileName, "成功");
            return file;
        } catch (IOException e) {
            log.error("文件名称由[{}]修改为[{}][{}]", multipartFile.getOriginalFilename(), fileName, "失败！", e);
            return null;
        }

    }
}
